<?php
    
	if (!isset($_GET["userid"]) || !isset($_GET["mid"]) || !isset($_GET["rating"])) {
        die();
    }
    
    $exists = false;
    
    include_once "include/constants.php";
	
    define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');

    try {
        $conn = new PDO('mysql:host='.DB_SERVER.';dbname='.DB_NAME, DB_USER, DB_PASS);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
         
        $stmt = $conn->prepare('select count(*) as cnt from user_ratings where userid = :userid and movieid = :movieid');
		$stmt->execute(array("userid" => $_GET["userid"], "movieid" => $_GET["mid"]));
        
        $moviedata = $stmt->fetch();
        if ($moviedata['cnt'] > 0) {
            $exists = true;
        }
        
        if ($exists) {
            $stmt = $conn->prepare('update user_ratings set rating = :rating where userid = :userid and movieid = :movieid');
            $stmt->execute(array("rating" => $_GET["rating"], "userid" => $_GET["userid"], "movieid" => $_GET["mid"]));
        }
        else {
            $stmt = $conn->prepare('insert into user_ratings (userid, rating, movieid)
                                    values (:userid, :rating, :movieid)');
            $stmt->bindParam('movieid', $_GET["mid"]);
            $stmt->bindParam('userid', $_GET["userid"]);
            $stmt->bindParam('rating', $_GET["rating"]);
            $stmt->execute();
        }
        
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
    
    echo "Done";
    
?>
